<?php

namespace App\Service\Common;

use App\Service\FuYou\FuYouService;
use Exception;
use Illuminate\Support\Facades\Log;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PhpImap;

class EmailService
{
    public string $emailHost, $emailPort, $contactEmail, $emailPassword, $sendUserName, $contactEmailCC;

    public function __construct()
    {
        $this->emailHost      = config('fuyou.email.host');                                                           //SMTP服务器
        $this->emailPort      = config('fuyou.email.port');                                                           //服务器端口 25 或者465 具体要看邮箱服务器支持
        $this->contactEmail   = config('fuyou.email.userName');                                                       //联系邮箱
        $this->emailPassword  = config('fuyou.email.password');                                                       //邮箱是授权码
        $this->sendUserName   = config('fuyou.email.sendUserName');                                                   //发件人名字
        $this->contactEmailCC = config('fuyou.contactEmail');                                                         //抄送邮箱（原颜路邮箱）
    }

    /**
     * 发送邮件
     * @param $receiveEmail
     * @param $receiveName
     * @param $title
     * @param $body
     * @param string $receiveCCEmail
     * @return array
     */
    public function sendEmail($receiveEmail, $receiveName, $title, $body, $receiveCCEmail = ""): array
    {
        $mail = new PHPMailer(true);                              // Passing `true` enables exceptions
        $data = [
            'code' => 200,
            'msg'  => $title . ' 邮件发送成功',
        ];
        try {
            $SMTPDebug = SMTP::DEBUG_OFF;
            if (config('app.env') == 'dev') {
                $SMTPDebug = SMTP::DEBUG_CONNECTION;// 调试模式输出
            }
            //服务器配置
            $mail->CharSet   = "UTF-8";                                                                                      //设定邮件编码
            $mail->SMTPDebug = $SMTPDebug;                                                                                   // 调试模式输出
            $mail->isSMTP();                                                                                                 // 使用SMTP
            $mail->Host       = $this->emailHost;                                                                            // SMTP服务器
            $mail->SMTPAuth = true;                                                                                          // 允许 SMTP 认证
            $mail->Username = $this->contactEmail;                                                                           // SMTP 用户名  即邮箱的用户名
            $mail->Password = $this->emailPassword;                                                                          // SMTP 密码  部分邮箱是授权码(例如163邮箱)
            $mail->SMTPSecure = 'ssl';                                                                                       // 允许 TLS 或者ssl协议
            $mail->Port       = $this->emailPort;                                                                            // 服务器端口 25 或者465 具体要看邮箱服务器支持

            $mail->setFrom($this->contactEmail, $this->sendUserName);     //发件人
            $mail->addAddress($receiveEmail, $receiveName);               // 收件人
            $mail->addReplyTo($this->contactEmail, $this->sendUserName);  //回复的时候回复给哪个邮箱 建议和发件人一致
//            $mail->addCC($this->contactEmailCC);                          //抄送
            if ($receiveCCEmail && is_array($receiveCCEmail) && count($receiveCCEmail)) {
                foreach ($receiveCCEmail as $v) {
                    $mail->addCC($v);                          //抄送邮箱
                }
            }

            //Content
            $mail->isHTML(true);                                    // 是否以HTML文档格式发送  发送后客户端可直接显示对应HTML内容
            $mail->Subject = $title;                                      //标题
            $mail->Body    = $body;                                       //正文
            $mail->send();
        } catch (Exception $e) {
            $data = [
                'code' => 500,
                'msg'  => $title . ' 邮件发送失败: ', $mail->ErrorInfo,
            ];
        }
        Log::info('发送邮件:',
            [
                'receiveEmail' => $receiveEmail,
                'receiveName'  => $receiveName,
                'title'        => $title,
                'body'         => $body,
                'res'          => $data,
            ]
        );
        return $data;
    }

    /**
     * 接收邮件
     */
    public  function receiveEmail(): array
    {
        $data = [
            'code' => 200,
            'msg'  => '接收邮件成功',
        ];

        try {
            $mailbox = new PhpImap\Mailbox(
                '{imap.qiye.aliyun.com}INBOX',              // 服务器地址和文件夹
                $this->contactEmail,                       // 邮箱的用户名
                $this->emailPassword,// 邮箱的密码
            );

            $mailsIds = $mailbox->searchMailbox('UNSEEN');//UNSEEN-未读的邮件

            // If $mailsIds is empty, no emails could be found
            if (!$mailsIds) {//找不到电子邮件
                throw new Exception('Mailbox is empty');
            }
            $data['count'] = count($mailsIds);
            $data['suc'] = $data['err'] = 0;
//            rsort($mailsIds);
            $mailbox->setAttachmentsIgnore(true);//允许在不需要附件时忽略附件，从而提高性能。
            $fuYouService = new FuYouService();
            // 获取邮件正文
            foreach ($mailsIds as $mailsId) {
                $email = $mailbox->getMail($mailsId);
                $emailData = [
                    'fromName'  => (string)($email->fromName ?? $email->fromAddress),//发件人
                    'fromEmail' => (string)$email->fromAddress,//发件邮箱
                    'to'        => (string)$email->toString,//收件人
                    'subject'   => (string)$email->subject,//主题
                    'messageId' => (string)$email->messageId,//messageId
                    'date'      => (string)date('Y-m-d H:i:s', strtotime($email->date)),//邮件时间
                ];

                //文件内容
                if ($email->textHtml) {
                    $emailData['body'] = $email->textHtml;
                } else {
                    $emailData['body'] = $email->textPlain;
                }
                $res = $fuYouService->receiveEmail($emailData);//处理邮件
                if ($res) {
                    $data['suc']++;
                    $mailbox->markMailAsRead($mailsId);//标记邮件已读
                } else {
                    $data['err']++;
                }
                Log::info('处理邮件:', ['emailData' => $emailData, 'res' => $res]);
            }
        } catch (Exception $e) {
            $data = [
                'code' => 500,
                'msg'  => '邮件接收失败: ', $e->getMessage(),
            ];
        }

        if (isset($mailbox) && $mailbox) {
            $mailbox->disconnect();
        }

        Log::info('接收邮件:', $data);
        return $data;
    }

}
